//join.js
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var uid = 0;

Page({
  data: {
    util: util,
    
    tc: 0,
    uid: 0, //当前登录用户Id
    token: '', //post请求时，当前登录用户token
    authData: {}, //未认证
    cataType: '',

    colorSet: '',

    chooseAddr: '',

    shopInfo: '',

    org_info: '',
    tel: '',

    showAuthView: false,
    authToastData: '',

    maxImgCount: 5,

    imgWH: 60,
    isIphone_x: false,
    nav_bgColor: '#ffffff',


    phone:'853',//手机号
    code:'',//验证码
    codename:'获取验证码',

    areaArr: '',
    areaIndex: 0,
    areaSelected: '',
  },



  wxAuthFail: true,
  inviteuid: '',

  addressInfo:{},

  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  onLoad: function(options) {
    var that = this;
    
    var tc = app.get_tc();
    var titleName = tc == 1 ? '註冊' : '注册';
    this.setData({
      tc: tc,
    });
    wx.setNavigationBarTitle({
      title: titleName,
    })

     wx.getSystemInfo({
      success: function(res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
        });
      }
    });

    app.getLoginUserInfo(function (res) {
      that.setData({
        uid: res.uid,
        token: res.token,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          imgWH: (res.windowWidth - 30) / 5 - 12
        });
      }
    })


    that.getYunfeiSet();
 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
  },
  //设置titlebar 样式
  resetNavColor: function() {
    var bg_color = '#f0f0f0';
    var fg_color = '#000000';
    if (this.data.colorSet) {
      bg_color = this.data.colorSet.titlebg;
      fg_color = this.data.colorSet.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  formAction: function(e){
    var that = this;
    let title = this.data.tc == 1 ? '溫馨提示' : '温馨提示';
    let content = this.data.tc == 1 ? '電話號碼是登錄的憑證，提交後不能修改，請確認是否用該號碼註冊' : '电话号码是登录的凭证，提交后不能修改，请确认是否用该号码注册';
    wx.showModal({
      title: title,
      content: content,
      success: function(res){
        if(res.confirm){
          that.joinSubmit(e);
        }
      }
    })
  },

  //填写资料提交
  joinSubmit: function(e) {
    var that = this;
    var realname = e.detail.value.name;
    var mobile = e.detail.value.mobile;
    var diqu = that.data.areaArr[e.detail.value.diqu].area;
    var daolu = e.detail.value.daolu;
    var dasha = e.detail.value.dasha;
    var password = e.detail.value.password;
    var code = e.detail.value.code;
    console.log(e);
    console.log(diqu);

    if (!realname) {
      app.dialog(that.data.tc == 1 ? '請填寫姓名' : '请填写姓名', 'loading');
      return;
    }
    if (!mobile) {
      app.dialog(that.data.tc == 1 ? '請填寫電話' : '请填写电话', 'loading');
      return;
    }
    if (!diqu) {
      app.dialog(that.data.tc == 1 ? '請填寫地區' : '请填写地区', 'loading');
      return;
    }
    if (!daolu) {
      app.dialog(that.data.tc == 1 ? '請填寫道路' : '请填写道路', 'loading');
      return;
    }
    if (!dasha) {
      app.dialog(that.data.tc == 1 ? '請填寫大廈' : '请填写大厦', 'loading');
      return;
    }
    if (!password) {
      app.dialog(that.data.tc == 1 ? '請填寫登錄密碼' : '请填写登录密码', 'loading');
      return;
    }
    if (!code) {
      app.dialog(that.data.tc == 1 ? '請填寫驗證碼' : '请填写验证码', 'loading');
      return;
    }
    
    that.addressInfo.name = realname;
    that.addressInfo.phone = mobile;
    that.addressInfo.diqu = diqu;
    that.addressInfo.daolu = daolu;
    that.addressInfo.dasha = dasha;
    that.addressInfo.address = diqu+daolu+dasha;
    that.addressInfo.password = password;

    
    var uid = that.data.uid;
    var token = that.data.token;
    console.log("uid = " + uid + "; token = " + token);


    var privatekey = utilMd5.hexMD5(uid + "checkaomensms" + token);
    var data = {
      "publickey": util.publiccode,
      "ac": "checkaomensms",
      "uid": uid,
      "privatekey": privatekey,
      "phone": mobile,
      "code": code,
    };
    
  
    util.actionSMS({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var resData = responseData.data;
        console.log(resData);
        if(resData.res == true){
          var privatekey = utilMd5.hexMD5(uid + "bindhuiyuan" + token);
          var data = {
            "publickey": util.publiccode,
            "ac": "bindhuiyuan",
            "uid": uid,
            "privatekey": privatekey,
            "realname": realname,
            "mobile": mobile,
            "phone": mobile,
            "address": diqu+daolu+dasha,
            "password": password,
          };
          
          console.log(" data:", data);
        
          util.api({
            data: data,
            method: 'POST',
            success: function (responseData) {
              var resData = responseData.data;
              console.log(resData);
              if(resData.res == true){
                // wx.setStorageSync('membercard', resData.membercard);
                that.saveAddress();
                wx.showToast({
                 title: '註冊成功',
                 icon: 'success',
                 duration: 2000,
                 success: function () {
                  setTimeout(function () {
                     wx.redirectTo({
                       url: '/pages/login/login?membercard='+mobile,
                      })
                  }, 2000);
                 }
                })

              }else{
                wx.showModal({
                  title: '提示',
                  content: resData.msg,
                  showCancel: false,
                })
              } 
              
            }
          });

        }else{
          wx.showModal({
            title: '提示',
            content: resData.msg,
            showCancel: false,
          })
        } 
        
      }
    });


    
  },


  saveAddress: function () {
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + "addaddress" + that.data.token);
    util.api({
      data: {
        "privatekey": privatekey,
        "ac": "addaddress",
        "uid": that.data.uid,
        "name": that.addressInfo.name,
        "phone": that.addressInfo.phone,
        "address": that.addressInfo.address,
        "psd_phone": '',
        "default": 1
      },
      method: "POST",
      success: function (responseData) {
        console.log("保存地址成功");
      }
    });
  },


  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      path = path.slice(6);
    }
    if (path) {
      wx.reLaunch({
        url: path,
      })
    }
  },



  quxiao:function(){
    console.log("quxiao");
    wx.navigateBack({
        delta: 1
      })
  },

  getPhoneValue:function(e){
    console.log(e);
    this.setData({
      phone:e.detail.value
    })
  },

  getCodeValue: function (e) {
    this.setData({
      code: e.detail.value
    })
  },

  getCode:function(){
    var that = this;
    console.log("shoujihao==",that.data.phone);
    var phone = that.data.phone;
    if (!phone) {
      app.dialog(that.data.tc == 1 ? '請填寫電話' : '请填写电话', 'loading');
      return;
    } else{
      that.setData({
        disabled: true
      })
      var privatekey = utilMd5.hexMD5(that.data.uid + "sendaomensms" + that.data.token);
      util.actionSMS({
        data: {
          "privatekey": privatekey,
          "ac": "sendaomensms",
          "uid": that.data.uid,
          "phone": that.data.phone,
        },
        method: "POST",
        success: function (responseData) {
          console.log(responseData)
          var resData = responseData.data;
          if(resData.res == true){
            wx.showToast({
              title: that.data.tc == 1 ? '短信發送成功' : '短信发送成功',
              icon: 'success',
              duration: 1000
            })

            var num = 61;
            var timer = setInterval(function () {
              num--;
              if (num <= 0) {
                clearInterval(timer);
                that.setData({
                  codename: '重新发送',
                  disabled: false
                })
  
              } else {
                that.setData({
                  codename: num + "s"
                })
              }
            }, 1000)
          }else{
            wx.showModal({
              title: '提示',
              content: resData.msg,
              showCancel: false,
            })
          }
          
        }
      })
      
    }
    
    
  },


  //获取运费设置
  getYunfeiSet: function () {
    wx.showLoading({
      title: 'loading',
    });
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        wx.hideLoading();
        console.log("运费：", responseData);
        var data = responseData.data;
        if (data.res == undefined) {
          that.setData({
            areaArr: data,
            areaSelected: data[0]
          })
          // let u_info = that.user_Info;
          // u_info.address1 = data[0].area;
          // that.user_Info.address = u_info.address1 + u_info.address2 + u_info.address3; 
        }
        
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //区域切换
  areaPicker: function (e) {
    let index = e.detail.value;
    let sel = this.data.areaArr[index];
    this.setData({
      areaIndex: index,
      areaSelected: sel
    });
  },


 

})